<script setup>
import { Upload ,Plus} from '@element-plus/icons-vue'
import {ref} from 'vue'
import { useUserStore } from '@/stores'
import { userUpdateUserAvatar } from '@/api/user'
import { ElMessage } from 'element-plus'
const userStore = useUserStore()
const imageUrl = ref(userStore.userInfo.user_pic)
const selectImg = (UploadFile)=>{
  console.log(UploadFile)
  imageUrl.value = URL.createObjectURL(UploadFile.raw)
  const reader = new FileReader()
  reader.readAsDataURL(UploadFile.raw)
  reader.onload = ()=>{
    imageUrl.value = reader.result
  }
}
const uploadRef = ref()
const handleSubmitImg = async ()=>{
  if(imageUrl.value){
  const res =  await userUpdateUserAvatar(imageUrl.value)
  await userStore.getUserInfo()
  ElMessage.success(res.data.message)

  }

}
</script>
<template>
  <page-container title="更换头像">
    <el-upload
      class="avatar-uploader"
      :show-file-list="false"
      :on-change="selectImg"
      :auto-upload="false"
      ref="uploadRef"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <img v-else src="../../assets/avatar.jpg" class="default-avatar">
    </el-upload>
    <div class="buttons">
      <el-button size="large" type="primary" :icon="Plus" @click="uploadRef.$el.querySelector('input').click()">选择图片</el-button>
      <el-button size="large" type="success" :icon="Upload" @click="handleSubmitImg">上传图片</el-button>
    </div>
  </page-container>
</template>
<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 250px;
      height: 250px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .default-avatar {
      font-size: 28px;
      color: #8c939d;
      width: 250px;
      height: 250px;
      text-align: center;
    }
  }
}
.buttons{
  margin-top: 25px;
}
</style>
